<template>
    <div>
        <el-breadcrumb separator-class="el-icon-caret-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--添加角色列表按钮-->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="setAddUserDialog = true">添加角色</el-button>
                </el-col>
            </el-row>

            <el-table :data="roleList" stripe border>
                <!--权限展开列-->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['vcenter','bdbottom',index1 === 0 ? 'bdtop' : '']"
                                v-for="(item1,index1) in scope.row.children" :key="item1.id">
                            <!--一级权限-->
                            <el-col :span="5">
                                <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>

                            <!--二级权限-->
                            <el-col :span="19">
                                <el-row :class="['vcenter',index2 === 0 ? '' : 'bdtop']"
                                        v-for="(item2,index2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!--三级权限-->
                                    <el-col :span="18">
                                        <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id"
                                                @close="removeRightById(scope.row,item3.id)">{{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!--索引列-->
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="角色操作" width="250px">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="editDialogVisibleShow(scope.row.id)"></el-button>
                        <el-button type="success" size="mini" icon="el-icon-setting"
                                   @click="showSetRightDialog(scope.row)" circle></el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="deleteRoleById(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>


        <!--分配权限对话框-->
        <el-dialog
                title="分配权限"
                :visible.sync="setRightDialogVisible"
                width="30%"
                @close="setDialogClose"
        >
            <!--树形控件-->
            <el-tree ref="treeRef" :data="rightsList" :default-checked-keys="defaultKeys" default-expand-all node-key="id"
                     show-checkbox :props="treeProps"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="authRights">确 定</el-button>
            </span>
        </el-dialog>

        <!--添加以及修改角色对话框-->
        <el-dialog
                title="添加角色"
                :visible.sync="setAddUserDialog"
                width="50%"
                @close="addUserDialogClose">
            <!--内容主体区-->
            <el-form :rules="addRoleRules" :model="Role" ref="addRoleRef" label-width="100px">
                <el-form-item label="用户名" prop="roleName">
                    <el-input v-model="Role.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                     <el-input  type="textarea" v-model="Role.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                 <el-button @click="setAddUserDialog = false">取 消</el-button>
                 <el-button type="primary" @click="addRole(Role.roleId)">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "Roles",
        data() {
            return {
                //角色列表
                roleList: [],
                //设置权限的弹框的显示
                setRightDialogVisible: false,
                //所有的权限的数据
                rightsList: [],
                //树形控件
                treeProps: {
                    children: 'children',
                    label: 'authName'
                },
                //默认选中的节点的Id数组
                defaultKeys: [],

                //设置添加role的弹框
                setAddUserDialog: false,
                Role: {
                    roleId: 0,
                },
                addRoleRules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色信息', trigger: 'blur'},
                    ]
                },

                //当前即将分配权限的Id
                RoleId: '',
            }

        },
        created() {
            this.getRolesList();
        },
        methods: {
            async getRolesList() {
                const {data} = await this.$http.get('roles');
                if (data.meta.status !== 200) return this.$message.error('获取角色信息失败');
                this.roleList = data.data;
            },

            //根据Id删除对应的权限
            async removeRightById(role, rightId) {
                //弹框提示
                const result = await this.$confirm('您确认要删除该用户的权限嘛', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (result === 'cancel') return this.$message.info('取消了删除')
                const {data} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
                if (data.meta.status !== 200) return this.$message.error('删除权限失败');
                //不建议直接重新发送请求，会导致展开列直接关闭
                //这里建议直接给role.children再次赋值，不会取重新刷新页面
                role.children = data.data;
            },

            //展示分配权限的对话框
            async showSetRightDialog(role) {
                this.RoleId = role.id;
                const {data} = await this.$http.get('rights/tree');
                if (data.meta.status !== 200) return this.$message.error('获取权限数据失败');
                //给权限数组赋值
                this.rightsList = data.data;
                //调用递归函数赋值到默认权限打开的数组
                this.getLeafKeys(role, this.defaultKeys);
                this.setRightDialogVisible = true;
            },

            //通过递归的形式获取角色所有的三级权限的Id保存到数组中
            getLeafKeys(node, arr) {
                if (!node.children) {
                    return arr.push(node.id);
                }
                //递归调用，遍历每一个节点
                node.children.forEach(item => this.getLeafKeys(item, arr));
            },

            //监听关闭权限对话框事件，设置的key数组重置
            setDialogClose() {
                this.defaultKeys = []
            },

            //监听user弹框的关闭
            addUserDialogClose() {
                this.Role = {roleId: 0};
            },

            //确认添加角色
            addRole(id) {
                this.$refs.addRoleRef.validate(async valid => {
                    if(valid){
                        if(id !== 0){
                            const {data} = await this.$http.put(`roles/${id}`,this.Role);
                            if (data.meta.status !== 200) return this.$message.error('修改角色失败');
                            this.$message.success('修改角色成功');
                        }else {
                            const {data} = await this.$http.post('roles',this.Role);
                            if (data.meta.status !== 201) return this.$message.error('添加角色失败');
                            this.$message.success('添加角色成功');
                        }
                        this.getRolesList();
                        this.setAddUserDialog = false;
                    }
                })
            },

            //根据Id删除对应的角色信息
            async deleteRoleById(id){
                const result = await this.$confirm('您确认要删除该角色嘛','提示',{
                    type: "warning",
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).catch(err => err);
                if (result === 'cancel') return this.$message.info('取消角色删除');
                const {data} = await this.$http.delete(`roles/${id}`);
                if (data.meta.status !== 200)return this.$message.error('删除角色失败');
                this.$message.success('删除角色成功');
                this.getRolesList();
            },

            //点击为角色分配权限
            async authRights(){
                const keys =  [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()];
                const idStr = keys.join(',');
                const {data} = await this.$http.post(`roles/${this.RoleId}/rights`,{rids: idStr});
                if (data.meta.status !== 200) return this.$message.error('分配权限失败');
                this.getRolesList();
                this.setRightDialogVisible = false;
                this.$message.success('分配权限成功');
            },

            //点击修改角色信息
             async editDialogVisibleShow(id){
                const {data} =  await this.$http.get(`roles/${id}`);
                if (data.meta.status !== 200) return this.$message.error('获取角色信息失败');
                this.Role = data.data;
                this.setAddUserDialog = true;
            },


        },

    }
</script>

<style scoped lang="less">
    .el-tag {
        margin: 10px;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>
